import 'dart:math';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/flowcard/model/card_info_resp.dart';
import 'package:tracker/pages/home/flowcard/model/device_config_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/pay/ali_pay_utils.dart';
import '../../../../common/pay/wxpay_utils.dart';
import '../mixin/flow_card_page_mixin.dart';

/// 流量卡页面
class FlowCardPage extends ConsumerStatefulWidget {
  const FlowCardPage({super.key});

  @override
  ConsumerState<FlowCardPage> createState() => _FlowCardPageState();
}

class _FlowCardPageState extends ConsumerState<FlowCardPage> with FlowCardPageMixin{
  bool showEmpty = true;
  CardInfoData cardInfoData = CardInfoData();
  bool showRechargeFlowButton = false;
  String rechargeFlowPage = '';
  late EasyRefreshController _refreshController;
  final ScrollController _scrollController = ScrollController();
  String _searchKeyword = ''; // 搜索关键词

  final alipayUtils = AliPayUtils();
  final wxpayUtils = WxpayUtils();
  @override
  void initState() {

    super.initState();
    final deviceInfo = ref.read(deviceInfoProvider);
    _searchKeyword = deviceInfo.iccid ?? "请输入iccid";
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      _refreshController.finishRefresh();
      _searchDeviceList();
      wxpayUtils.registerWechatResp((resp) {
        XLogger.info('wxpayUtils exMsg: ${resp}');

        if (resp.isSuccessful == true) {
          // XLogger.info('拉起小程序: ${resp.errorCode} ${resp.errorMsg}, isSuccessful: ${resp.isSuccessful}');
          // XLogger.info('拉起小程序 exMsg: ${resp.extMsg}');
          // if (resp.isSuccessful) {
          //   // 支付成功
          ToastUtils.showSimpleDialog(context,
              title: '提示', content: '套餐购买成功', confirmTitle: '好的', confirmCallback: () {});
          // 刷新套餐信息
          // } else {
          //   // 支付失败
          //   ToastUtils.showToast('支付失败');
          // }
        }else {
          ToastUtils.showToast('支付失败');
        }
      });
    });
    alipayUtils.listenPay((resp) {
      XLogger.info('VIP支付结果：${resp.resultStatus}');
      if (resp.isSuccessful) {
        // 支付成功
        // ToastUtils.showSimpleDialog(context,
        //     title: '提示', content: '套餐购买成功', confirmTitle: '好的', confirmCallback: () {});
        ToastUtils.showToast('购买成功');
        // 刷新套餐信息
      } else {
        // 支付失败
        ToastUtils.showToast('支付失败');
      }
    });


    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  _doPullDownRefresh() async {
    _refreshController.finishRefresh();
  }

  _buildLoading() {
    return Container(
      alignment: Alignment.center,
      child: CircularProgressIndicator(
        color: AppTheme.themeConfig.primaryColor,
      ),
    );
  }

  // JSON数据过滤逻辑
  _searchDeviceList() async {
    if (_searchKeyword.length <= 0) {
      ToastUtils.showToast('请输入iccid');
      XLogger.error('请输入iccid');
      return ;
    }
    final queryParams = {
      'iccid':_searchKeyword,// "89860837142470096259",
    };

    final res = await get<CardInfoResp, CardInfoResp>('$newBaseULr/sim/info',
        queryParameters: queryParams, decodeType: CardInfoResp());
    res.when(success: (CardInfoResp resp) {
      if (resp.code == 200) {
        // ToastUtils.showToast('查询成功');

        setState(() {
          cardInfoData = resp.data!;
        });
        _refreshController.finishRefresh();
      } else {
        ToastUtils.showToast(resp.msg ?? '获取设备列表失败');
      }
      setState(() {
        showLoading = false;
      });
    }, failure: (String msg, int code) {
      XLogger.error('获取设备列表失败 code: $code msg: $msg');
    });
  }




  /// 内容视图
  Widget _buildBody() {
    final statusBarHeight = MediaQuery.of(context).padding.top;

    return SingleChildScrollView(

      padding: EdgeInsets.only(top: statusBarHeight + 50),

      child: Column(
        children: [
          // ICCID显示区域
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.white,
                  Colors.white.withOpacity(0.9),
                ],
              ),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(
                color: AppTheme.themeConfig.primaryColor.withOpacity(0.2),
                width: 1,
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 12,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                        AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                      ],
                    ),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.sim_card,
                    color: AppTheme.themeConfig.primaryColor,
                    size: 24,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'ICCID',
                        style: TextStyle(
                          fontSize: 12,
                          color: AppTheme.themeConfig.secondaryTextColor,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        _searchKeyword,
                        style: TextStyle(
                          fontSize: 15,
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontWeight: FontWeight.w700,
                          letterSpacing: 0.5,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          // 流量信息卡片
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.white,
                  Colors.white.withOpacity(0.95),
                ],
              ),
              borderRadius: BorderRadius.circular(20),
              border: Border.all(
                color: AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                width: 1,
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.15),
                  blurRadius: 20,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Column(
              children: [
                // 环形进度（模拟）
                Stack(
                  alignment: Alignment.center,
                  children: [
                    // Container(
                    //   width: 100,
                    //   height: 100,
                    //   decoration: BoxDecoration(
                    //     gradient: RadialGradient(
                    //       colors: [Colors.green, Colors.teal, Colors.blue],
                    //       // 中心偏移（左上角为-1,-1，右下角为1,1）
                    //       center: const Alignment(-0.3, -0.3),
                    //       radius: 0.7,
                    //     ),
                    //     borderRadius: BorderRadius.circular(12),
                    //   ),
                    // ),
                    Container(
                      width: 120,
                      height: 120,
                      decoration:  BoxDecoration(

                        shape: BoxShape.circle,
                        gradient: SweepGradient(
                          // startAngle: -pi,
                          // endAngle: pi * 2 - pi ,
                          transform: GradientRotation(-pi / 2),
                          colors: [
                            Colors.red,
                            Colors.blue,
                          ],
                          stops:  [0.0, ((cardInfoData.monthUsedFlow ?? 0) / (cardInfoData.monthFlow ?? 1).toDouble())],
                        ),
                      ),
                    ),
                    Container(
                      width: 100,
                      height: 100,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.white,
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        '总流量 \n${(cardInfoData.monthFlow ?? 0) + (cardInfoData.flowNumber ?? 0)}MB',

                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.blue,
                        ),
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 8),

                // 剩余流量标题
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    cardInfoData.monthFlow == null ? '剩余流量 --' : '剩余流量 \n${(((cardInfoData.monthFlow ?? 0) + (cardInfoData.flowNumber ?? 0) - (cardInfoData.monthUsedFlow ?? 0)))}MB',

                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),

                const SizedBox(height: 8),

                // 总计/剩余流量 小卡片
                // Container(
                //   padding: const EdgeInsets.symmetric(
                //     horizontal: 12,
                //     vertical: 8,
                //   ),
                //   decoration: BoxDecoration(
                //     color: Colors.blue[50],
                //     borderRadius: BorderRadius.circular(4),
                //   ),
                // child: Row(
                //   children: [
                //     Text(
                //       '总计流量 ${shengyu((cardInfoData.monthFlow ?? 0).toDouble())}',
                //       style: TextStyle(
                //         color: Colors.blue[900],
                //         fontSize: 14,
                //       ),
                //     ),
                //     const SizedBox(width: 16),
                //     Text(
                //       '剩余流量 ${(((cardInfoData.monthFlow ?? 0) - (cardInfoData.monthUsedFlow ?? 0)))}MB',
                //       style: TextStyle(
                //         color: Colors.blue[600],
                //         fontSize: 14,
                //         fontWeight: FontWeight.bold,
                //       ),
                //     ),
                //   ],
                // ),
                // ),

                const SizedBox(height: 8),

                // 套餐标题
                const Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '流量套餐',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),

                const SizedBox(height: 8),

                // 进度条
                LinearProgressIndicator(
                  value: (cardInfoData.monthUsedFlow ?? 0) / (cardInfoData.monthFlow ?? 1).toDouble(), // 已用2GB / 总计60GB
                  backgroundColor: Colors.grey[300],
                  valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
                ),

                const SizedBox(height: 8),

                // 套餐详情
                Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                        text: '已用:${shengyu((cardInfoData.monthUsedFlow ?? 0))}',
                        style: TextStyle(color: Colors.black87),
                      ),
                      TextSpan(
                        text: '剩余${(((cardInfoData.monthFlow ?? 0) + (cardInfoData.flowNumber ?? 0) - (cardInfoData.monthUsedFlow ?? 0)))}MB',
                        style: TextStyle(color: Colors.grey[600]),
                      ),
                    ],
                  ),
                ),

                const SizedBox(height: 4),
                Text(
                  '服务到期时间：${cardInfoData.overdueTime ?? ""}',
                  style: TextStyle(color: Colors.grey[600], fontSize: 12),
                ),

                const SizedBox(height: 8),

                // ICCID等信息
                InfoRow(title: 'ICCID', content: '${cardInfoData.iccid ?? "--"}',showCopyButton: true),
                InfoRow(title: '卡号', content: '${cardInfoData.simId ?? "--"}',showCopyButton: true),
                InfoRow(title: 'SIM卡状态', content: '${cardInfoData.flowServStatus == 0 ? "停用" : "正常"}'),
                InfoRow(title: '已用流量', content: '${shengyu(cardInfoData.monthUsedFlow ?? 0)}'),
              ],
            ),
          ),
          // 温馨提示
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.orange.shade50,
                  Colors.orange.shade50.withOpacity(0.5),
                ],
              ),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(
                color: Colors.orange.shade200,
                width: 1,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(6),
                      decoration: BoxDecoration(
                        color: Colors.orange.shade100,
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.info_outline,
                        color: Colors.orange.shade700,
                        size: 16,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '温馨提示',
                      style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w700,
                        color: Colors.orange.shade900,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                _buildTipItem('请仔细核对充值号码，充值成功后无法退款'),
                const SizedBox(height: 6),
                _buildTipItem('流量卡充值可能会延迟到账，若长时间未到账，请联系客服处理'),
                const SizedBox(height: 6),
                _buildTipItem('超出套餐流量和短信会停用，流量数据会有一定延迟，仅供参考'),
              ],
            ),
          ),

          // 底部充值按钮
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: GestureDetector(
              onTap: () {
                XLogger.error(_searchKeyword);
                context.push('${RouterManager.charge}?iccid=${Uri.encodeComponent(_searchKeyword)}').then((value) {
                  XLogger.error("_searchDeviceList");
                  _searchDeviceList();
                });
              },
              child: Container(
                height: 56,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [
                      AppTheme.themeConfig.primaryColor,
                      AppTheme.themeConfig.primaryColor.withOpacity(0.8),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(16),
                  boxShadow: [
                    BoxShadow(
                      color: AppTheme.themeConfig.primaryColor.withOpacity(0.4),
                      blurRadius: 12,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(
                      Icons.account_balance_wallet,
                      color: Colors.white,
                      size: 24,
                    ),
                    const SizedBox(width: 12),
                    const Text(
                      '立即充值',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w700,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),

        ],
      ),

    );
  }


  Widget _buildTipItem(String text) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: const EdgeInsets.only(top: 6),
          width: 4,
          height: 4,
          decoration: BoxDecoration(
            color: Colors.orange.shade600,
            shape: BoxShape.circle,
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            text,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[700],
              height: 1.5,
            ),
          ),
        ),
      ],
    );
  }

  String shengyu(double liuliang) {
    // int liuliang =  (cardInfoData.monthFlow ?? 0) - (cardInfoData.monthUsedFlow ?? 0);
    if (liuliang < 1024) {
      return "${liuliang}MB";

    }else {
      double liuliangGB = (liuliang / 1024 * 10).round() / 10.0;
      return "${liuliangGB}GB";

    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: const Text(
            '流量卡',
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.w700),
          ),
          centerTitle: true,
          backgroundColor:  Colors.transparent,
          elevation: 0,
          iconTheme: const IconThemeData(color: Colors.white),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ),
        // backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
        body:Container(
          height: double.infinity,
          decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/page_bg.png'),
                fit: BoxFit.cover,
              )),
          child: EasyRefresh(
              controller: _refreshController,
              onRefresh: () async {
                _doPullDownRefresh();
              },
              child: _buildBody()),
        )
    );


  }
}

/// 信息行组件（如 ICCID、卡号等）
// 信息行组件（支持复制功能）
class InfoRow extends StatelessWidget {
  final String title;
  final String content;
  final bool showCopyButton; // 控制是否显示复制按钮

  const InfoRow({
    Key? key,
    required this.title,
    required this.content,
    this.showCopyButton = false,
  }) : super(key: key);

  // 复制到剪贴板功能
  void _copyToClipboard(BuildContext context, String text) async {
    if (text.isEmpty || text == "--") return;

    await Clipboard.setData(ClipboardData(text: text));
    // 显示复制成功提示
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('已复制${title}：$text'),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 统一行高的关键：使用固定高度的容器并设置对齐方式
    return Container(
      height: 24, // 设置固定行高，根据实际字体大小调整
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center, // 垂直居中对齐
        children: [
          // 标题部分 - 固定宽度确保对齐
          SizedBox(
            width: 80, // 根据最长标题设置合适宽度
            child: Text(
              '$title：',
              style: const TextStyle(
                color: Colors.black87,
                fontSize: 14,
              ),
            ),
          ),
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center, // 垂直居中
              children: [
                Text(
                  content,
                  style: TextStyle(
                    color: Colors.grey[700],
                    fontSize: 14,
                  ),
                  // 防止文本过长导致高度变化
                  overflow: TextOverflow.ellipsis,
                ),
                if (showCopyButton)
                  IconButton(
                    icon: const Icon(Icons.copy, size: 16, color: Colors.blue),
                    onPressed: () => _copyToClipboard(context, content),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(
                      minHeight: 20,
                      minWidth: 20,
                    ),
                    tooltip: '复制',
                    splashRadius: 16, // 减小点击反馈区域
                  )
              ],
            ),
          ),
        ],
      ),
    );

  }
}

